'use client'

import { useState, useEffect } from 'react'
import { 
  PlusIcon, 
  PlayIcon, 
  PauseIcon, 
  StopIcon,
  TrashIcon,
  EyeIcon,
  ClockIcon,
  ArrowPathIcon
} from '@heroicons/react/24/outline'

interface ExtractionTask {
  id: number
  name: string
  keywords: string
  maxCount: number
  status: string
  progress: number
  totalFound: number
  extracted: number
  lastRunAt: string | null
  nextRunAt: string | null
  isRecurring: boolean
  interval: number | null
  autoDownloadFiles: boolean
  autoExtractText: boolean
  createdAt: string
  creator: {
    username: string
  }
  executions: {
    id: number
    status: string
    startedAt: string | null
    completedAt: string | null
    videosFound: number
    videosExtracted: number
  }[]
}

export default function TasksPage() {
  const [tasks, setTasks] = useState<ExtractionTask[]>([])
  const [loading, setLoading] = useState(true)
  const [showCreateForm, setShowCreateForm] = useState(false)
  const [selectedTask, setSelectedTask] = useState<ExtractionTask | null>(null)
  const [showTaskDetail, setShowTaskDetail] = useState(false)

  useEffect(() => {
    fetchTasks()
    // 每30秒刷新一次任务状态
    const interval = setInterval(fetchTasks, 30000)
    return () => clearInterval(interval)
  }, [])

  const fetchTasks = async () => {
    try {
      const response = await fetch('/api/tasks')
      if (response.ok) {
        const data = await response.json()
        setTasks(data.tasks)
      }
    } catch (error) {
      console.error('Failed to fetch tasks:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleCreateTask = () => {
    setShowCreateForm(true)
  }

  const handleStartTask = async (taskId: number) => {
    try {
      const response = await fetch(`/api/tasks/${taskId}/start`, {
        method: 'POST'
      })

      if (response.ok) {
        alert('任务已开始执行')
        fetchTasks()
      } else {
        const data = await response.json()
        alert(data.error || '启动任务失败')
      }
    } catch (error) {
      alert('网络错误，请重试')
    }
  }

  const handlePauseTask = async (taskId: number) => {
    try {
      const response = await fetch(`/api/tasks/${taskId}/pause`, {
        method: 'POST'
      })

      if (response.ok) {
        alert('任务已暂停')
        fetchTasks()
      } else {
        alert('暂停任务失败')
      }
    } catch (error) {
      alert('网络错误，请重试')
    }
  }

  const handleStopTask = async (taskId: number) => {
    try {
      const response = await fetch(`/api/tasks/${taskId}/stop`, {
        method: 'POST'
      })

      if (response.ok) {
        alert('任务已停止')
        fetchTasks()
      } else {
        alert('停止任务失败')
      }
    } catch (error) {
      alert('网络错误，请重试')
    }
  }

  const handleDeleteTask = async (taskId: number) => {
    if (!confirm('确定要删除这个任务吗？')) return

    try {
      const response = await fetch(`/api/tasks/${taskId}`, {
        method: 'DELETE'
      })

      if (response.ok) {
        alert('任务删除成功')
        fetchTasks()
      } else {
        alert('删除任务失败')
      }
    } catch (error) {
      alert('网络错误，请重试')
    }
  }

  const getStatusBadge = (status: string) => {
    const statusConfig = {
      pending: { color: 'bg-gray-100 text-gray-800', text: '待执行' },
      running: { color: 'bg-blue-100 text-blue-800', text: '执行中' },
      completed: { color: 'bg-green-100 text-green-800', text: '已完成' },
      failed: { color: 'bg-red-100 text-red-800', text: '执行失败' },
      paused: { color: 'bg-yellow-100 text-yellow-800', text: '已暂停' }
    }
    
    const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.pending
    
    return (
      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${config.color}`}>
        {config.text}
      </span>
    )
  }

  const parseKeywords = (keywordsStr: string) => {
    try {
      return JSON.parse(keywordsStr)
    } catch {
      return []
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
      </div>
    )
  }

  return (
    <div>
      <div className="sm:flex sm:items-center">
        <div className="sm:flex-auto">
          <h1 className="text-xl font-semibold text-gray-900">任务管理</h1>
          <p className="mt-2 text-sm text-gray-700">
            创建和管理TikTok内容提取任务
          </p>
        </div>
        <div className="mt-4 sm:mt-0 sm:ml-16 sm:flex-none">
          <button
            type="button"
            onClick={handleCreateTask}
            className="inline-flex items-center justify-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 sm:w-auto"
          >
            <PlusIcon className="-ml-1 mr-2 h-5 w-5" />
            创建任务
          </button>
        </div>
      </div>

      {/* 任务列表 */}
      <div className="mt-8 grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
        {tasks.map((task) => (
          <div key={task.id} className="bg-white overflow-hidden shadow rounded-lg">
            <div className="p-6">
              <div className="flex items-center justify-between">
                <div className="flex items-center">
                  <div className="flex-shrink-0">
                    <div className="w-8 h-8 bg-indigo-500 rounded-full flex items-center justify-center">
                      <ClockIcon className="w-5 h-5 text-white" />
                    </div>
                  </div>
                  <div className="ml-4">
                    <h3 className="text-lg font-medium text-gray-900 truncate">
                      {task.name}
                    </h3>
                    <p className="text-sm text-gray-500">
                      创建者: {task.creator.username}
                    </p>
                  </div>
                </div>
                <div className="flex-shrink-0">
                  {getStatusBadge(task.status)}
                </div>
              </div>

              <div className="mt-4">
                <div className="flex items-center text-sm text-gray-500">
                  <span>关键词: </span>
                  <div className="ml-1 flex flex-wrap gap-1">
                    {parseKeywords(task.keywords).slice(0, 3).map((keyword: string, index: number) => (
                      <span key={index} className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-800">
                        {keyword}
                      </span>
                    ))}
                    {parseKeywords(task.keywords).length > 3 && (
                      <span className="text-xs text-gray-400">+{parseKeywords(task.keywords).length - 3}</span>
                    )}
                  </div>
                </div>
                
                <div className="mt-2 text-sm text-gray-500">
                  <div>每次提取: {task.maxCount} 个视频</div>
                  <div>已提取: {task.extracted} / {task.totalFound}</div>
                  {task.isRecurring && (
                    <div>循环间隔: {task.interval} 小时</div>
                  )}
                </div>

                {/* 自动化选项显示 */}
                {(task.autoDownloadFiles || task.autoExtractText) && (
                  <div className="mt-2 flex flex-wrap gap-1">
                    {task.autoDownloadFiles && (
                      <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                        自动下载
                      </span>
                    )}
                    {task.autoExtractText && (
                      <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                        自动提取文案
                      </span>
                    )}
                  </div>
                )}

                {task.status === 'running' && (
                  <div className="mt-3">
                    <div className="flex justify-between text-sm text-gray-600">
                      <span>进度</span>
                      <span>{task.progress}%</span>
                    </div>
                    <div className="mt-1 w-full bg-gray-200 rounded-full h-2">
                      <div 
                        className="bg-indigo-600 h-2 rounded-full transition-all duration-300"
                        style={{ width: `${task.progress}%` }}
                      ></div>
                    </div>
                  </div>
                )}

                <div className="mt-4 text-xs text-gray-400">
                  {task.lastRunAt && (
                    <div>最后运行: {new Date(task.lastRunAt).toLocaleString()}</div>
                  )}
                  {task.nextRunAt && (
                    <div>下次运行: {new Date(task.nextRunAt).toLocaleString()}</div>
                  )}
                </div>
              </div>

              <div className="mt-6 flex justify-between">
                <div className="flex space-x-2">
                  {task.status === 'pending' || task.status === 'paused' ? (
                    <button
                      onClick={() => handleStartTask(task.id)}
                      className="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
                    >
                      <PlayIcon className="w-4 h-4 mr-1" />
                      开始
                    </button>
                  ) : task.status === 'running' ? (
                    <>
                      <button
                        onClick={() => handlePauseTask(task.id)}
                        className="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded text-white bg-yellow-600 hover:bg-yellow-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-yellow-500"
                      >
                        <PauseIcon className="w-4 h-4 mr-1" />
                        暂停
                      </button>
                      <button
                        onClick={() => handleStopTask(task.id)}
                        className="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
                      >
                        <StopIcon className="w-4 h-4 mr-1" />
                        停止
                      </button>
                    </>
                  ) : (
                    <button
                      onClick={() => handleStartTask(task.id)}
                      className="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                      <ArrowPathIcon className="w-4 h-4 mr-1" />
                      重新运行
                    </button>
                  )}
                </div>
                
                <div className="flex space-x-2">
                  <button
                    onClick={() => {
                      setSelectedTask(task)
                      setShowTaskDetail(true)
                    }}
                    className="inline-flex items-center px-3 py-1.5 border border-gray-300 text-xs font-medium rounded text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                  >
                    <EyeIcon className="w-4 h-4 mr-1" />
                    详情
                  </button>
                  <button
                    onClick={() => handleDeleteTask(task.id)}
                    className="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
                  >
                    <TrashIcon className="w-4 h-4 mr-1" />
                    删除
                  </button>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {tasks.length === 0 && (
        <div className="text-center py-12">
          <ClockIcon className="mx-auto h-12 w-12 text-gray-400" />
          <h3 className="mt-2 text-sm font-medium text-gray-900">暂无任务</h3>
          <p className="mt-1 text-sm text-gray-500">开始创建您的第一个提取任务</p>
          <div className="mt-6">
            <button
              type="button"
              onClick={handleCreateTask}
              className="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              <PlusIcon className="-ml-1 mr-2 h-5 w-5" />
              创建任务
            </button>
          </div>
        </div>
      )}

      {/* 创建任务表单模态框 */}
      {showCreateForm && (
        <CreateTaskModal 
          onClose={() => setShowCreateForm(false)}
          onSuccess={() => {
            setShowCreateForm(false)
            fetchTasks()
          }}
        />
      )}

      {/* 任务详情模态框 */}
      {showTaskDetail && selectedTask && (
        <TaskDetailModal
          task={selectedTask}
          onClose={() => {
            setShowTaskDetail(false)
            setSelectedTask(null)
          }}
        />
      )}
    </div>
  )
}

// 创建任务模态框组件
function CreateTaskModal({ onClose, onSuccess }: { onClose: () => void, onSuccess: () => void }) {
  const [formData, setFormData] = useState({
    name: '',
    keywords: '',
    maxCount: 10,
    isRecurring: false,
    interval: 24,
    autoExtractText: false,
    autoDownloadFiles: false
  })
  const [loading, setLoading] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)

    try {
      const keywordsArray = formData.keywords.split(',').map(k => k.trim()).filter(k => k)
      
      const response = await fetch('/api/tasks', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ...formData,
          keywords: JSON.stringify(keywordsArray)
        }),
      })

      if (response.ok) {
        alert('任务创建成功')
        onSuccess()
      } else {
        const data = await response.json()
        alert(data.error || '创建任务失败')
      }
    } catch (error) {
      alert('网络错误，请重试')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
      <div className="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-md bg-white">
        <div className="mt-3">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-medium text-gray-900">创建提取任务</h3>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600"
            >
              <span className="sr-only">关闭</span>
              ✕
            </button>
          </div>
          
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700">任务名称</label>
              <input
                type="text"
                required
                value={formData.name}
                onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                placeholder="输入任务名称"
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700">关键词</label>
              <input
                type="text"
                required
                value={formData.keywords}
                onChange={(e) => setFormData(prev => ({ ...prev, keywords: e.target.value }))}
                className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                placeholder="输入关键词，用逗号分隔"
              />
              <p className="mt-1 text-sm text-gray-500">例如: 美食,旅游,科技</p>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700">每次提取数量</label>
              <input
                type="number"
                min="1"
                max="100"
                required
                value={formData.maxCount}
                onChange={(e) => setFormData(prev => ({ ...prev, maxCount: parseInt(e.target.value) }))}
                className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              />
            </div>
            
            <div className="flex items-center">
              <input
                type="checkbox"
                id="isRecurring"
                checked={formData.isRecurring}
                onChange={(e) => setFormData(prev => ({ ...prev, isRecurring: e.target.checked }))}
                className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
              />
              <label htmlFor="isRecurring" className="ml-2 block text-sm text-gray-900">
                循环执行任务
              </label>
            </div>
            
            {formData.isRecurring && (
              <div>
                <label className="block text-sm font-medium text-gray-700">循环间隔（小时）</label>
                <input
                  type="number"
                  min="1"
                  max="168"
                  required
                  value={formData.interval}
                  onChange={(e) => setFormData(prev => ({ ...prev, interval: parseInt(e.target.value) }))}
                  className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                />
              </div>
            )}

            {/* 自动化选项 */}
            <div className="space-y-3">
              <h4 className="text-sm font-medium text-gray-900">自动化选项</h4>

              <div className="flex items-center">
                <input
                  id="autoDownloadFiles"
                  type="checkbox"
                  checked={formData.autoDownloadFiles}
                  onChange={(e) => setFormData(prev => ({ ...prev, autoDownloadFiles: e.target.checked }))}
                  className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                />
                <label htmlFor="autoDownloadFiles" className="ml-2 block text-sm text-gray-900">
                  自动下载文件（视频、音频、封面）
                </label>
              </div>

              <div className="flex items-center">
                <input
                  id="autoExtractText"
                  type="checkbox"
                  checked={formData.autoExtractText}
                  onChange={(e) => setFormData(prev => ({ ...prev, autoExtractText: e.target.checked }))}
                  className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                />
                <label htmlFor="autoExtractText" className="ml-2 block text-sm text-gray-900">
                  自动提取文案（下载完成后自动进行语音识别/OCR）
                </label>
              </div>

              {formData.autoExtractText && (
                <div className="ml-6 text-xs text-gray-500">
                  <p>• 有音频的视频将使用语音识别</p>
                  <p>• 无音频的视频将使用OCR识别</p>
                </div>
              )}
            </div>

            <div className="flex justify-end space-x-3 pt-4">
              <button
                type="button"
                onClick={onClose}
                className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                取消
              </button>
              <button
                type="submit"
                disabled={loading}
                className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
              >
                {loading ? '创建中...' : '创建任务'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  )
}

// 任务详情模态框组件
function TaskDetailModal({ task, onClose }: { task: ExtractionTask, onClose: () => void }) {
  return (
    <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
      <div className="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-2/3 shadow-lg rounded-md bg-white">
        <div className="mt-3">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-medium text-gray-900">任务详情</h3>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600"
            >
              <span className="sr-only">关闭</span>
              ✕
            </button>
          </div>
          
          <div className="space-y-6">
            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
              <div>
                <h4 className="text-sm font-medium text-gray-900">基本信息</h4>
                <dl className="mt-2 space-y-1">
                  <div>
                    <dt className="text-sm text-gray-500">任务名称:</dt>
                    <dd className="text-sm text-gray-900">{task.name}</dd>
                  </div>
                  <div>
                    <dt className="text-sm text-gray-500">创建者:</dt>
                    <dd className="text-sm text-gray-900">{task.creator.username}</dd>
                  </div>
                  <div>
                    <dt className="text-sm text-gray-500">状态:</dt>
                    <dd className="text-sm text-gray-900">{task.status}</dd>
                  </div>
                  <div>
                    <dt className="text-sm text-gray-500">每次提取数量:</dt>
                    <dd className="text-sm text-gray-900">{task.maxCount}</dd>
                  </div>
                </dl>
              </div>
              
              <div>
                <h4 className="text-sm font-medium text-gray-900">执行统计</h4>
                <dl className="mt-2 space-y-1">
                  <div>
                    <dt className="text-sm text-gray-500">找到视频总数:</dt>
                    <dd className="text-sm text-gray-900">{task.totalFound}</dd>
                  </div>
                  <div>
                    <dt className="text-sm text-gray-500">已提取数量:</dt>
                    <dd className="text-sm text-gray-900">{task.extracted}</dd>
                  </div>
                  <div>
                    <dt className="text-sm text-gray-500">执行进度:</dt>
                    <dd className="text-sm text-gray-900">{task.progress}%</dd>
                  </div>
                  <div>
                    <dt className="text-sm text-gray-500">循环任务:</dt>
                    <dd className="text-sm text-gray-900">{task.isRecurring ? `是 (${task.interval}小时)` : '否'}</dd>
                  </div>
                </dl>
              </div>
            </div>
            
            <div>
              <h4 className="text-sm font-medium text-gray-900">关键词</h4>
              <div className="mt-2 flex flex-wrap gap-2">
                {JSON.parse(task.keywords).map((keyword: string, index: number) => (
                  <span key={index} className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800">
                    {keyword}
                  </span>
                ))}
              </div>
            </div>
            
            <div>
              <h4 className="text-sm font-medium text-gray-900">执行历史</h4>
              <div className="mt-2">
                {task.executions.length > 0 ? (
                  <div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg">
                    <table className="min-w-full divide-y divide-gray-300">
                      <thead className="bg-gray-50">
                        <tr>
                          <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wide">
                            状态
                          </th>
                          <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wide">
                            开始时间
                          </th>
                          <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wide">
                            完成时间
                          </th>
                          <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wide">
                            找到/提取
                          </th>
                        </tr>
                      </thead>
                      <tbody className="bg-white divide-y divide-gray-200">
                        {task.executions.slice(0, 5).map((execution) => (
                          <tr key={execution.id}>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                              {execution.status}
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                              {execution.startedAt ? new Date(execution.startedAt).toLocaleString() : '-'}
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                              {execution.completedAt ? new Date(execution.completedAt).toLocaleString() : '-'}
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                              {execution.videosFound} / {execution.videosExtracted}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                ) : (
                  <p className="text-sm text-gray-500">暂无执行记录</p>
                )}
              </div>
            </div>
          </div>
          
          <div className="mt-6 flex justify-end">
            <button
              onClick={onClose}
              className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              关闭
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}
